package cn.da.shuai.cool.common.web.interceptor;

import cn.da.shuai.cool.common.constant.Const;
import cn.da.shuai.cool.common.util.PageUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import cn.da.shuai.cool.common.web.wrapper.ReusableRequestWrapper;

import java.io.IOException;
import java.util.Map;

@Slf4j
@Component
public class PageInterceptor implements HandlerInterceptor {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        setPageParameters(request);
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    private void setPageParameters(HttpServletRequest request) {
        try {

            // 首先尝试从查询参数中获取分页信息
            String pageNumStr = request.getParameter(Const.PAGE_NUM);
            String pageSizeStr = request.getParameter(Const.PAGE_SIZE);

            if (StringUtils.isNotBlank(pageNumStr) && StringUtils.isNotBlank(pageSizeStr)) {
                // 如果URL参数中有分页信息，优先使用URL参数
                PageUtil.setPage(Integer.parseInt(pageNumStr), Integer.parseInt(pageSizeStr));
                return;
            }

            // 如果URL参数中没有分页信息，尝试从请求体中获取
            if (isJsonRequest(request)) {
                Map<?, ?> bodyParams = getRequestBody(request);
                if (bodyParams != null && bodyParams.containsKey(Const.PAGE_NUM) && bodyParams.containsKey(Const.PAGE_SIZE)) {
                    Object pageNum = bodyParams.get(Const.PAGE_NUM);
                    Object pageSize = bodyParams.get(Const.PAGE_SIZE);

                    // 处理数字类型，支持Integer和Number类型
                    int pageNumValue, pageSizeValue;
                    if (pageNum instanceof Number) {
                        pageNumValue = ((Number) pageNum).intValue();
                    } else if (pageNum instanceof String) {
                        pageNumValue = Integer.parseInt((String) pageNum);
                    } else {
                        return;
                    }

                    if (pageSize instanceof Number) {
                        pageSizeValue = ((Number) pageSize).intValue();
                    } else if (pageSize instanceof String) {
                        pageSizeValue = Integer.parseInt((String) pageSize);
                    } else {
                        return;
                    }

                    PageUtil.setPage(pageNumValue, pageSizeValue);
                }
            }
        } catch (Exception e) {
            log.error("Error parsing page parameters in page interceptor", e);
        }
    }

    /**
     * 判断是否为JSON请求
     */
    private boolean isJsonRequest(HttpServletRequest request) {
        String contentType = request.getContentType();
        return contentType != null && contentType.contains(MediaType.APPLICATION_JSON_VALUE);
    }

    /**
     * 从请求体中获取参数
     */
    private Map<?,?> getRequestBody(HttpServletRequest request) {
        if (request instanceof ReusableRequestWrapper wrapper) {
            try {
                byte[] content = wrapper.getBody();
                if (content.length > 0) {
                    String jsonBody = new String(content, wrapper.getCharacterEncoding());
                    return objectMapper.readValue(jsonBody, Map.class);
                }
            } catch (IOException e) {
                log.debug("Failed to read request body", e);
            }
        }
        return null;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        PageUtil.clearPage();
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
